#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <signal.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "list.h"


struct song_t {
	char name[40];
	struct list_head list;
};

struct share_t {
	struct list_head *pos;
	long id;
};

static char key;
static int shm_id;
static struct list_head head;

void play_music(void)
{
	struct share_t *share;
	struct song_t *song;

	share = (struct share_t *)shmat(shm_id, NULL, 0);

	while(1)
	{
		list_for_each(share->pos, &head)
		{
			song = list_entry(share->pos, struct song_t, list);

			printf("current music is : %s\n", song->name);
			
			if(fork() == 0)
			{
				share->id = getpid();

				execlp("/bin/madplay", "madplay", song->name, NULL);
			}
			else
				wait(NULL);

		}
		printf("all song has been played\n");
	}
}

int main(int argc, char *argv[])
{
	DIR *dir;
	struct dirent *dirent;
	struct song_t *song;
	int fd;
	struct share_t *share;
	int first = 1;
	long start_id;
	int cnt = 0;
	
	INIT_LIST_HEAD(&head);
		
	dir = opendir("/mp3");	
	if(dir == NULL)
	{
		printf("opendir /mp3 error\n");
		return -1;
	}

	fd = open("/dev/s3c_buttons", O_RDONLY);
	if(fd < 0)
	{
		printf("cann't open s3c_buttons device\n");
		closedir(dir);
		return -1;
	}

	while((dirent = readdir(dir)) != NULL)
	{
		if((dirent->d_type == 8) && (strstr(dirent->d_name, ".mp3") != NULL))
		{
			song = malloc(sizeof(struct song_t));
			if(song == NULL)
			{        
				printf("malloc error\n");
				return -1;
			}
			strcpy(song->name, dirent->d_name);
			list_add(&song->list, &head);
			cnt ++;
		}
	}

	if(cnt == 0)
	{
		printf("no music find\n");
		goto exit;
	}

	shm_id = shmget(IPC_PRIVATE, sizeof(struct share_t), IPC_CREAT);
	share = (struct share_t *)shmat(shm_id, NULL, 0);

	
	for(;;)
	{
		read(fd, &key, 1);

		if(key == 1)	//play music
		{
			if(first)
			{
				first = 0;
				start_id = fork();
				if(start_id == 0)
					play_music();
			}
		}
		if(key == 2) 	//stop music
		{
			if(!first)
				kill(share->id, SIGSTOP);	
		}
		if(key == 3)
		{
			if(!first)
				kill(share->id, SIGCONT);
		}
		if(key == 4)	//prev music
		{
			printf("\n prev music... \n");
			if(!first)
			{
				if(share->pos->prev == &head)
					share->pos = head.prev->prev;
				else
					share->pos = share->pos->prev->prev;
				kill(share->id, SIGKILL);
			}
		}
		if(key == 5)	//next music
		{
			printf("\n next music... \n");
			
			kill(share->id, SIGKILL);	
		}
		if(key == 6)	//exit
		{
			kill(share->id, SIGKILL);
			kill(start_id, SIGKILL);
			goto exit;
		}
	}

exit:
	
	close(fd);
	closedir(dir);

	printf("mp3 player exit\n");
	
	return 0;
}

